package com.ucenter.server.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.system.auth.AuthUtil;
import com.system.auth.model.AuthClient;
import com.system.comm.model.KvEntity;
import com.system.comm.model.Page;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;
import com.ucenter.server.user.dao.WebsiteDao;
import com.ucenter.server.user.enums.WebsiteStatus;
import com.ucenter.server.user.pojo.Website;
import com.ucenter.server.user.service.WebsiteService;

/**
 * website的Service
 * @author autoCode
 * @date 2018-02-06 15:18:19
 * @version V1.0.0
 */
@Component
public class WebsiteServiceImpl implements WebsiteService {

	@Autowired
	private WebsiteDao websiteDao;
	
	@Override
	public ResponseFrame saveOrUpdate(Website website) {
		ResponseFrame frame = new ResponseFrame();
		Website org = get(website.getWebsiteId());
		if(org == null) {
			websiteDao.save(website);
		} else {
			websiteDao.update(website);
		}
		AuthClient client = new AuthClient(website.getWebsiteId(), website.getName(), website.getDomain(), website.getSecret(), "http://127.0.0.1/callback.htm");
		if(WebsiteStatus.NORMAL.getCode() == website.getStatus().intValue()) {
			AuthUtil.updateAuthClient(client);
		} else if(WebsiteStatus.STOP.getCode() == website.getStatus().intValue()) {
			AuthUtil.delAuthClient(website.getWebsiteId());
		}
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public Website get(String websiteId) {
		return websiteDao.get(websiteId);
	}

	@Override
	public ResponseFrame pageQuery(Website website) {
		website.setDefPageSize();
		ResponseFrame frame = new ResponseFrame();
		int total = websiteDao.findWebsiteCount(website);
		List<Website> data = null;
		if(total > 0) {
			data = websiteDao.findWebsite(website);
			for (Website web : data) {
				web.setStatusName(WebsiteStatus.getText(web.getStatus()));
			}
		}
		Page<Website> page = new Page<Website>(website.getPage(), website.getSize(), total, data);
		frame.setBody(page);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}
	
	@Override
	public ResponseFrame delete(String websiteId) {
		ResponseFrame frame = new ResponseFrame();
		websiteDao.delete(websiteId);
		AuthUtil.delAuthClient(websiteId);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public List<Website> findUse() {
		return websiteDao.findByStatus(WebsiteStatus.NORMAL.getCode());
	}

	@Override
	public String getName(String websiteId) {
		Website website = get(websiteId);
		return website == null ? null : website.getName();
	}

	@Override
	public List<KvEntity> findKvUse() {
		List<KvEntity> data = new ArrayList<KvEntity>();
		List<Website> list = findUse();
		for (Website website : list) {
			data.add(new KvEntity(website.getWebsiteId(), website.getName()));
		}
		return data;
	}
}